<?php
namespace Member\Controller;
use Member\Controller\InitController;
class DownloadController extends InitController{
	public function _initialize(){
		header("content-type:text/html;charset=utf-8");
		parent::_initialize();
		$this->db = D('Download');
		$this->member_db = D('Member');
	}
	public function index(){
		$id = (int) I('id');
		$modelid = (int) I('modelid');
		$ident = I('ident');
		if($id < 1 || $modelid < 1 || empty($ident)){
			$this->error('参数错误');
		}
		$models = getcache('model','commons');
		$tablename = $models[$modelid]['tablename'];
		if(empty($tablename)){$this->error('参数错误');}
		$picfile = M($tablename.'_data')->getFieldById($id, 'picfile');
		$picfile = unserialize($picfile);
		if(!isset($picfile[$ident]) || empty($picfile[$ident])){$this->error('参数错误');}
		$picinfo = $picfile[$ident];
		
		$_point = (int) $picinfo['point'];
		$_url = $picinfo['url'];
				
		if($_point < 1) {
			$this->download($picinfo['url']);	
		}
		 /* 判断该尺寸的图片是否已被下载 */
		$sqlMap = array();
		$sqlMap['userid'] = $this->userid;
		$sqlMap['modelid'] = $modelid;
		$sqlMap['document_id'] = $id;
		$sqlMap['ident'] = $ident;
		$_isDownload = $this->db->where($sqlMap)->count();

		if (!$_isDownload) {
			if($this->userinfo['point'] >= $_point) {
				/* 写入下载记录表 */
				$info = $sqlMap;
				$info['point'] = $_point;
				$info['num'] = 1;
				$result = $this->db->update($info);
				if(!$result) {
					$this->error($this->getError());
				}
				/* 扣除用户积分 */
				$this->member_db->where("`userid` = '".$this->userid."'")->setDec('point',  $_point);
				$this->download($picinfo['url']);
			} else {
				/* 积分不够的情况下直接到吉祥卡购买 */
				$this->error('您的下载点不足，请先充值！', U('Member/LuckCard/lucky_card'));
			}
		} else {
			$this->db->where($sqlMap)->setInc('num', 1);
			$this->download($picinfo['url']);			
		}
	}
	
	/* 下载图片 fuck！！ */
	private function download($pic) {
		$pic = str_replace('http://'.$_SERVER['HTTP_HOST'].__ROOT__.'/uploadfile', SITE_PATH.'/uploadfile', $pic);
		if(is_file($pic) && file_exists($pic)) {
			header("Content-Type: application/force-download");
			header("Content-Disposition: attachment; filename=".basename($pic));
			readfile($pic);
			exit;
		}else{
			echo "文件不存在！";
			exit;
		}
	}
}